import {
  createSlice,
  PayloadAction,
  createAsyncThunk,
  ActionReducerMapBuilder
} from "@reduxjs/toolkit"
import axios from "axios"

interface ProductSearchState {
  loading: boolean
  error: string | null
  data: any
  pagination: any
}

const initialState: ProductSearchState = {
  loading: true,
  error: null,
  data: null,
  pagination: null
}

export const searchProduct = createAsyncThunk(
  "productSearch/searchProduct",
  async (
    paramaters: {
      keywords: string
      nextPage: number | string
      pageSize: number | string
    },
    thunkAPI
  ) => {
    let url = `http://123.56.149.216:8080/api/touristRoutes?pageNumber=${paramaters.nextPage}&pageSize=${paramaters.pageSize}`
    if (paramaters.keywords) {
      url += `&keyword=${paramaters.keywords}`
    }
    const response = await axios.get(url)
    return {
      data: response.data,
      pagination: JSON.parse(response.headers["x-pagination"])
    }
  }
)

export const productSearchSlice = createSlice({
  name: "productSearch",
  initialState,
  reducers: {},
  extraReducers: (builder: ActionReducerMapBuilder<ProductSearchState>) => {
    builder
      .addCase(searchProduct.pending, (state) => {
        // 处理pending状态，比如设置加载标志
        // return { ...state, loading: true };
        state.loading = true
      })
      .addCase(searchProduct.fulfilled, (state, action) => {
        // 处理fulfilled状态，使用action.payload更新state
        state.data = action.payload.data
        state.pagination = action.payload.pagination
        state.loading = false
        state.error = null
      })
      .addCase(searchProduct.rejected, (state, action) => {
        // 处理rejected状态，比如设置错误信息
        state.loading = false
        // state.error = action.payload
      })
  }
})
